package com.ajax.controller;


import com.ajax.Student;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author 从卿
 * @create 2022/5/6-22:23
 */
@Controller
public class AjaxController {
    @RequestMapping(value = "/rr.ajax")
    public void ajaxReturnResult(HttpServletResponse response,String name, Integer age) throws IOException {
        System.out.println("姓名是："+name);
        Student student = new Student();
        student.setName(name);
        student.setAge(age);
//        把对象转为json
        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(student);
        System.out.println("服务端对象转为json");
//        输出JSON,响应ajax
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println(json);
        writer.flush();
        writer.close();
    }

    /**
     * 对象传值
     * @param name
     * @param age
     * @return
     */
    @RequestMapping(value = "/rrr.ajax")
    @ResponseBody
    public  Student ajaxReturnResult(String name,Integer age){
        System.out.println("姓名："+name+"，年龄："+age);
        Student student=new Student();
        student.setName(name);
        student.setAge(age);
        return  student;
    }

    /**
     * list集合传值
     * @param name
     * @param age
     * @return
     */
    @RequestMapping(value = "/listRR.ajax")
    @ResponseBody
    public List<Student> listReturnResult(String name, Integer age){
        Student student=new Student();
        student.setName("张三");
        student.setAge(18);
        Student student1=new Student();
        student1.setName("李四");
        student1.setAge(18);
        List<Student> list=new ArrayList<>();
        list.add(student);
        list.add(student1);
        return  list;
    }
    /**
     * String类型传值
     *
     */
    @RequestMapping(value = "/stringRR.ajax",produces="text/plain;charset=utf-8")
//    此处text-plain后面为双引号，不然会报错
    @ResponseBody
    public String  stringRR(String name, Integer age){
        System.out.println("控制器返回String类型，是数据，不是视图");
        return "springmvc String类型传值";
    }
}
